import {Component, OnDestroy, OnInit, ViewEncapsulation} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {EventsService} from '@core/events/events.service';
import {ToolbarService} from '@shared/components/toolbar/toolbar.service';
import {ToolsService} from '@shared/service/tools/tools.service';
import {UserActivityService} from '@shared/service/user-activity/user-activity.service';
import {ValidationService} from '@shared/service/validator/validator.service';
import {Subscription} from 'rxjs';


@Component({
  selector: 'register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class RegisterComponent implements OnInit, OnDestroy {
  public registerForm: FormGroup;
  public account: AbstractControl; // 手机号
  public verifyCode: AbstractControl; // 验证码
  public isRegister = false;  // 是否已注册
  public invalidPhoneNumber = false;
  public phoneError = '';
  public timer = '发送验证码';
  public subscription: Subscription = new Subscription();
  public dataStore = {
    imgValidateCode: '', // 图片验证码
    randomKey: '' // 图片验证码随机key
  };
  public stateStore = {
    isSended: false  // 短信验证码发送状态
  };

  constructor(
    public router: Router,
    public formBuilder: FormBuilder,
    public userActicityService: UserActivityService,
    public tools: ToolsService,
    public toolBarService: ToolbarService,
    public events: EventsService
  ) {
    this.registerForm = this.formBuilder.group({
      'account': ['', [Validators.required, ValidationService.accountValidator]],
      'verifyCode': ['', [Validators.required]],
      'validateCode': ['', [Validators.required, Validators.minLength(4), Validators.maxLength(4)]]
    });
    this.events.publish('progressbar:hide');
  }

  ngOnInit() {
    this.getImgValidateCode();
    this.subscription.add(
      this.toolBarService.unfoldNav()
    );
    this.subscription.add(
      this.registerForm.valueChanges
        .debounceTime(300)   // 开始输入之后500毫秒内只取最新的结果
        .distinctUntilChanged()  // 去掉跟之前输入一样的结果
        .subscribe(form => {
          if (this.registerForm.controls['account'].errors) {   // 判断账号框是否有错
            if (!this.registerForm.controls['account'].hasError('required')) {   // 如果输入框非空
              this.invalidPhoneNumber = this.registerForm.controls['account'].errors['invalidPhoneNumber'];   // 取验证结果
              this.phoneError = ValidationService.getValidatorErrorMessage('invalidPhoneNumber');
            } else {  // 用户名是空
              this.phoneError = ValidationService.getValidatorErrorMessage('phoneNumberNull');
            }
          } else {
            this.invalidPhoneNumber = false;   // 否则就不显示错误提示
          }
        })
    );
  }

  gotoFindPsw() {
    this.router.navigate(['/login/set-psw']);
  }

  /**
   * @description 获取短信验证码
   * @author ouyqx-691
   * @date 2017-09-20
   */
  getSMSCode() {
    const SMSCode = {
      phone: this.registerForm.value.account,
      operateType: '1'
    };
    this.userActicityService.getSMSCode(SMSCode).subscribe((res) => {
      if (res.result === '0') {
        this.stateStore.isSended = true; // 验证码发送成功   Note:开发环境默认为666666
        this.SMSCodeCountDown(60);
      } else if (res.result === '4002') {   // 后台返回4002去取的话是缺少参数的提示，所以这个接口单独写
        this.tools.showToast('手机号码不正确');
      } else {
        this.getImgValidateCode();
        this.tools.showStatusCodeMsg(res.result);
      }
    });
  }

  // 前往设置密码
  goSetPassword() {
    // 核实验证码
    const form = this.registerForm.value;
    const validateSMSCode = {
      validateMsg: form.verifyCode,
      validateType: '5',
      somethingStr: form.account,
      operateType: '1'
    };
    this.subscription.add(
      this.userActicityService.checkSMSCode(validateSMSCode).subscribe((res) => {
        if (res.result === '0') {
          this.router.navigate(['/auth/set-psw'], {queryParams: {phone: form.account, code: form.verifyCode}});
          return false;
        }
        this.tools.showStatusCodeMsg(res.result);
      })
    );
  }

  // 发送验证码倒计时
  SMSCodeCountDown(second: number) {
    if (second !== 0) {
      //  e.target.preventDefault()
      this.timer = `${second--}秒`;
      setTimeout(() => {
        this.SMSCodeCountDown(second);
      }, 1000);
    } else {
      this.timer = '发送验证码';
    }
  }

  goProtocal() {
    this.router.navigate(['/auth/registration-protocol']);
  }

  /**
   * @description 前台处理表单
   * @author ouyqx-691
   * @date 2017-09-19
   */
  checkForm() {
    const controls = this.registerForm.controls;

    if (controls['account'].value === '') {
      this.tools.showToast('手机号码不能为空');
    } else if (controls['validateCode'].value === '') {
      this.tools.showToast('验证码不能为空');
    } else {
      this.checkValidateCode();
    }
  }

  /**
   * @description 获取图片验证码
   * @author ouyqx-691
   * @date 2017-09-19
   * @param params{type:类型,width:宽度,height:高度}
   */
  checkValidateCode() {
    const formData = this.registerForm.value;
    const params = {
      type: 2,
      randomKey: this.dataStore.randomKey,
      imgValidateCode: this.registerForm.value['validateCode']
    };

    this.userActicityService.checkImgValidateCode(params).subscribe(res => {
      if (res.result === '0' && res.data) {
        this.getSMSCode();
      } else {
        this.getImgValidateCode();
        this.tools.showToast('验证码输入有误，请重新输入');
      }
    });
  }

  /**
   * @description 获取图片验证码
   * @author ouyqx-691
   * @date 2017-09-19
   * @param params{type:类型,width:宽度,height:高度}
   */
  getImgValidateCode() {
    const params = {
      type: 2,
      width: 100,
      height: 45
    };
    this.userActicityService.getImgValidateCode(params).subscribe(res => {
      if (res.result === '0') {
        this.dataStore.randomKey = res.data.key;
        this.dataStore.imgValidateCode = res.data.image;
      }
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
